<?php

namespace app\controllers;

use Yii;
use app\models\User;
use app\components\PHPMailer;

class VerifyController extends \app\components\Controller
{
	/**
     * Modify the email for send a mail to user's emai address
     * @author : nonglei
     * @date   : 30/07/2014
     */
    public function actionModifyemail()
    {
        if(isset($_POST['data']))
        {
            $user = User::model()->findByAttributes(array('user_name'=>yii::app()->user->name));
            if($user == null)
            {
                $arr = array(
                    'type'=>1,
                    'message'=>yii::t('other/defualt','Error:Please login first.'),
                );
                echo json_encode($arr);
            }
            else
            {
                $verifyCode = $this->createRandomStr(6);
                /**
                 * 存入session
                 */
                $session = Yii::app()->session;
                $session['emailTok_'.$name] = $verifyCode;
                $time = $session['emailTok_Time_'.$name];
                if($time == null )
                {
                    $session['emailTok_Time_'.$name] = time();
                }
                else
                {
                    $con = time() - $time;
                    if($con < 60)
                    {
                        $arr = array(
                            'type'=>5,
                            'message'=>'Please do not submit in a short time',
                            'sec'=>(60-$con),
                        );
                        echo json_encode($arr);exit;
                    }
                    else
                    {
                        $session['emailTok_Time_'.$name] = time();
                    }
                }
                $verifyCode = md5($verifyCode);
                $name = $user->user_name;
                $url = Yii::app()->request->getHostInfo().yii::app()->baseUrl.'/user/modifyEmail/tok/'.$verifyCode;

                $body = "<p>".yii::t('other/default','Dear')." $name,"."</p>";
                $body = $body."<p>".yii::t('other/default','This is a letter from Goj account management automated message, to help you reset your email address for Goj')."</p>";
                $body = $body."<p>".yii::t('other/default','Please visit the following link and fill in the new Email address').":</p>";
                $body = $body."<p><b><a href=\"".$url."\">".$url."</a></b></p>";
                $body = $body."<p>".yii::t('other/default','If you have any suggestions you can contact us by repeat this mail.')."</p>";
                $body = $body."<p>".yii::t('other/default','Goj Manager Team')."</p>";
                $body = $body."<p>"."<a herf=\"http://onlinejudge.guet.edu.cn/guetoj/\">http://onlinejudge.guet.edu.cn/guetoj</a>"."</p>";
                $subject = yii::t('other/default','Goj Modify Email Address');
                $address = $user->email_address;

                if($this->sendEmail($body,$subject,$address,$name))
                {
                    $arr = array(
                        'type'=>2,
                        'message'=>yii::t('other/defualt','Sending success!'),
                    );
                    echo json_encode($arr);
                }
                else
                {
                    $arr = array(
                        'type'=>2,
                        'message'=>yii::t('other/defualt','Sending failure. Please try again.'),
                    );
                    echo json_encode($arr);
                }
            }
        }

    }
    public function actionRetrievepassword()
    {
        if(isset($_POST['data']))
        {
            $username = $_POST['username'];
            $email = $_POST['email'];
            if($username == null)
            {
                $arr = array(
                    'type'=>1,
                    'message'=>Yii::t('Mail','UserName cant\'t be Empty.'),
                );
                echo json_encode($arr);
            }
            else if($email == null)
            {
                $arr = array(
                    'type'=>2,
                    'message'=>Yii::t('Mail','Email cant\'t be Empty.'),
                );
                echo json_encode($arr);
            }
            else
            {
                $user = User::findByUsername($username);
                if($user->email !== $email)
                {
                    $arr = array(
                        'type'=>3,
                        'message'=>Yii::t('Mail','This Email is not suitable for this UserName.'),
                    );
                    echo json_encode($arr);
                }
                else
                {
                    $verifyCode = $this->createRandomStr(6);
                    $name = $user->user_name;
                    /**
                     * 存入session
                     */
                    $session = Yii::$app->session;
                    $session->open();
                    $session['verifyCode_'.$name] = $verifyCode;
                    $time = $session['verifyCode_Time_'.$name];
                    if($time == null )
                    {
                        $session['verifyCode_Time_'.$name] = time();
                    }
                    else
                    {
                        $con = time() - $time;
                        if($con < 60)
                        {
                            $arr = array(
                                'type'=>5,
                                'message'=>'Please do not submit in a short time',
                                'sec'=>(60-$con),
                            );
                            echo json_encode($arr);exit;
                        }
                        else
                        {
                            $session['verifyCode_Time_'.$name] = time();
                        }
                    }

                    $body = "<p>".Yii::t('Mail','Dear')." $name,"."</p>";
                    $body = $body."<p>".Yii::t('Mail','This is a letter from Goj account management automated message, to help you reset your password for Goj')."</p>";
                    $body = $body."<p>".Yii::t('Mail','Please fill the following code in the inputBox "Email Verification"').":</p>";
                    $body = $body."<p><b>".$verifyCode."</b></p>";
                    $body = $body."<p>".Yii::t('Mail','If you have any suggestions you can contact us by repeat this mail.')."</p>";
                    $body = $body."<p>".Yii::t('Mail','Goj Manager Team')."</p>";
                    $body = $body."<p>"."<a herf=\"http://onlinejudge.guet.edu.cn/guetoj/\">http://onlinejudge.guet.edu.cn/guetoj</a>"."</p>";
                    $subject = yii::t('Mail','GuetNoticeSystem Retrieve Password');
                    $address = $user->email;

                    if($this->sendEmail($body,$subject,$address,$name))
                    {
                        $arr = array(
                            'type'=>4,
                            'message'=>Yii::t('Mail','Sending success!'),
                        );
                        echo json_encode($arr);
                    }
                    else
                    {
                         $arr = array(
                            'type'=>4,
                            'message'=>yii::t('Mail','Sending failure. Please try again.'),
                        );
                        echo json_encode($arr);
                    }
                }
            }
        }
    }
    public function createRandomstr($length)
    {
        $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符
        $strlen = 62;
        while($length > $strlen){
            $str .= $str;
            $strlen += 62;
        }
        $str = str_shuffle($str);
        return substr($str,0,$length);
    }
    public function sendEmail($body,$subject,$address,$name)
    {
            $mail = new PHPMailer(); //建立邮件发送类
            $mail->CharSet ="UTF-8";
            $mail->IsSMTP(); // 使用SMTP方式发送
            $mail->Host = "smtp.exmail.qq.com"; // 您的企业邮局域名
            $mail->Post = 25; // 您的企业邮局域名
            $mail->SMTPAuth = true; // 启用SMTP验证功能
            $mail->Username = "guetoj@rayor.cn"; // 邮局用户名(请填写完整的email地址)
            $mail->Password = "goj2014"; // 邮局密码

            $mail->From = "guetoj@rayor.cn"; //邮件发送者email地址
            $mail->FromName = yii::t('other/default','GuetOJ Manager Team');
            $mail->AddAddress("$address", "$name");//收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")

            ////$mail->AddAttachment("/var/tmp/file.tar.gz"); // 添加附件
            $mail->IsHTML(true); // set email format to HTML //是否使用HTML格式
            $mail->Subject = "$subject"; //邮件标题
            $mail->Body = "$body"; //邮件内容
            //$mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //附加信息，可以省略
            if(!$mail->send())
            {
                $this->errorMessage = $mail->ErrorInfo;
                return false;
            }
            else
            {
                return true;
            }
    }
}
